﻿using System.Text.RegularExpressions;
using System.Text;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;

namespace LogServerApi
{
    public static class Utils
    {
        public static readonly bool IsInDocker = Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true";

        private readonly static Regex reFramework;
        private readonly static Encoding defaultEncoding;
        private readonly static Regex reSanitizeFileName;

        static Utils()
        {
            reFramework = new Regex(@"\.net\sframework", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            // 加载编码(.NetFramework平台不需要加载)
            if (!reFramework.IsMatch(RuntimeInformation.FrameworkDescription))
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            }
            defaultEncoding = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.OEMCodePage) : Encoding.UTF8;

            var invalidChars = new string(Path.GetInvalidPathChars().Concat(Path.GetInvalidFileNameChars()).Distinct().ToArray());
            reSanitizeFileName = new Regex($"[{Regex.Escape(invalidChars)}]", RegexOptions.Compiled);
        }

        public static Encoding DefaultEncoding => defaultEncoding;

        #region Path
        /// <summary>
        /// 启动目录(当前执行的程序的入口程序集文件所在目录)
        /// </summary>
        /// <returns></returns>
        public static string GetStartupFolder()
        {
            return Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location)!;
        }

        /// <summary>
        /// 当前进程的可执行文件所在目录
        /// </summary>
        /// <returns></returns>
        public static string GetExecuteDir()
        {
            return Path.GetDirectoryName(Process.GetCurrentProcess()?.MainModule?.FileName)!;
        }

        /// <summary>
        /// 获取某个路径的绝对路径
        /// </summary>
        /// <param name="filePath">路径</param>
        /// <param name="basePath">先对参考路径(默认为当前进程的可执行文件所在目录)</param>
        /// <returns></returns>
        public static string GetRealPath(string filePath, string? basePath = null)
        {
            if (Path.IsPathRooted(filePath))
            {
                return filePath;
            }
            return Path.GetFullPath(Path.Combine(string.IsNullOrWhiteSpace(basePath) ? GetExecuteDir() : basePath, filePath));
        }

        public static string GetEntryFolder()
        {
            return GetRealPath(".", GetStartupFolder());
        }

        public static string SanitizeFileName(string path)
        {
            return reSanitizeFileName.Replace(path, string.Empty);
        }
        #endregion

    }
}
